<?php

namespace Post\Model;

use Carbon\Carbon;
use Common\Model\BaseModel;
//use Biz\AliyunLive;
use Ruben\Aliyun\Mts;
use Common\Model\ModelException;

class PostModel extends BaseModel {

    protected $_auto = [
        ['create_time', 'time', self::MODEL_INSERT, 'function'],
        ['title', 'replaceBadWord', self::MODEL_BOTH, 'callback'],
    ];
    protected $_validate = [
        ['title', 'require', '内容不能为空'],
        ['user_id', 'require', '发布人不能为空'],
    ];
    protected $_scope = [
        'valid' => [
            'where' => ['audit' => 1, 'delete_time' => 0, 'is_transed' => 'Y'],
        ]
    ];

    public function publish($uid, $data) {

        $post = [
            'user_id' => $uid,
            'title' => $data['title'],
            'details' => $data['details'],
            'pic' => $data['pic'] ? : '',
            'type' => $data['type'],
            'who_show' => $data['who_show'],
            'audit' => 1, // 默认
            'is_transed' => "Y",
        ];

        if ($data['type'] == 2) {
            $post['video'] = $data['video'];
            $post['is_transed'] = 'N';
        }

        $postModel = D('Post');
        $postModel->create($post);
        if ($id = $postModel->add()) {
            return $id;
        } else {
            throw new ModelException(80001, $postModel->getError());
        }
    }

    public function autofill() {
        $config = C('sdk.oss');
        $posts = D('Post')->where(['type' => '2', 'is_transed' => 'N'])->select();
        if (count($posts) > 0) {
            $mts = new Mts($config);
            foreach ($posts as $post) {
                $useCdn = strpos($post['video'], $config['cdn']) !== false;
                $video = $post['video'];
                $mediaUrl = $useCdn ? str_replace($config['cdn'], "{$config['bucket']}.{$config['endpoint']}", $video) : $video;
                if ($mediaUrl) {
                    $mediaInfo = $mts->queryMediaListByURL("http://" . $mediaUrl);
                    $media = $mediaInfo->MediaList->Media;
                    $cover_url = 0;
                    if (count($media)) {
                        $cover_url = $media[0]->CoverURL;
                        $post['cover_url'] = $cover_url;
  //                    $post['video'] = $media['trans_url'] ? : $media['url'];
                        $post['is_transed'] = $cover_url?'Y':'N';
                        M('Post')->save($post);
                    }
                }
            }
        }
    }

    public function praise($postId, $userId) {
        $zan = D('PostZan')->where(['post_id' => $postId, 'user_id' => $userId])->find();
        if ($zan) {
            throw new ModelException(80002);
        }
        D('Post')->where(['post_id' => $postId])->setInc('zan_num', 1);
        D('PostZan')->add([
            'post_id' => $postId,
            'user_id' => $userId,
            'create_time' => time(),
            'create_ip' => get_client_ip(),
        ]);
        return true;
    }

    protected function _after_find(&$record, $options) {
        $config = C('sdk.oss');
        $user = get_user();
//        $favoriteIds = M('PostFavorite')->where(['user_id' => $user['id']])->getField('post_id', true);
        if ($record['pic']) {
            $pics = explode(',', $record['pic']);
            $record['pic'] = array_map(function($pic) use ($config) {
                return oss_images_auto_fill($pic, $config['styles']);
            }, $pics);
        } else {
            $record['pic'] = [];
        }
//        if ($record['cover_url'])
//            $record['cover_url'] = $record['cover_url'] . '?x-oss-process=style/video_cover';
        if ($record['create_time']) {
            Carbon::setLocale('zh');
            $record['human_time'] = Carbon::createFromTimestamp($record['create_time'])->diffForHumans();
        }
        $zanPostIds = D('PostZan')->where(['user_id' => $user['id']])->getField('post_id', true);
        $record['is_zan'] = in_array($record['post_id'], $zanPostIds) ? 1 : 0;
//        $record['is_favorite'] = in_array($record['post_id'], $favoriteIds) ? 1 : 0;
    }

    public function _after_select(&$records, $options) {
        if (empty($records))
            return;
        $user = get_user();
//        $favoriteIds = M('PostFavorite')->where(['user_id' => $user['id']])->getField('post_id', true);
        $zanPostIds = D('PostZan')->where(['user_id' => $user['id']])->getField('post_id', true);
        Carbon::setLocale('zh');
        $config = C('sdk.oss');

        /* 查询动态中包含的video信息 */
        $videos = array_column($records, 'video');

        foreach ($records as &$record) {
            if ($record['pic']) {
                $pics = explode(',', $record['pic']);

                $record['pic'] = array_map(function($pic) use ($config) {
                    return oss_images_auto_fill($pic, $config['styles']);
                }, $pics);
            } else {
                $record['pic'] = [];
            }
            if ($record['create_time']) {

                $record['human_time'] = Carbon::createFromTimestamp($record['create_time'])->diffForHumans();
            }
//            if ($record['cover_url'])
//                $record['cover_url'] = $record['cover_url'] . '?x-oss-process=style/video_cover';
//                $record['cover_url'] = $record['cover_url'];
            if (empty($zanPostIds)) {
                $record['is_zan'] = 0;
            } else {
                $record['is_zan'] = in_array($record['post_id'], $zanPostIds) ? 1 : 0;
            }
            if(empty($record['to_user_id'])){
                $record['is_favorite'] = 0;
            }else{
                 $record['is_favorite'] = 1;
            }
        }
        return $records;
    }

    protected function implodeImage($images) {
        return $images ? implde(',', $images) : '';
    }

    /**
     * 过滤敏感词
     * @param string $data
     * @return string
     */
    protected function replaceBadWord($data) {
        $v = unserialize(D('Setting')->getByK('articlesensitivewords')['v']);
        $words = empty($v['word']) ? [] : explode('|', trim($v['word'], '|'));
        return filter_badwords($data, $words);
    }

}
